package com.xiumu.config.interceptor;

import cn.hutool.core.util.StrUtil;
import com.xiumu.common.core.constants.XiuMuConst;
import com.xiumu.common.core.utils.IncreaseUtils;
import com.xiumu.common.core.utils.IpUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.management.ManagementFactory;

/**
 * 请求追踪拦截
 * 给每一个请求设置一个 traceId
 *
 * @Author XiuMu
 * @Date 2023/2/8 11:12
 **/
@Slf4j
public class TraceInterceptor implements HandlerInterceptor {

    /**
     * 生成 traceID
     * 客户端 IP.当前请求时间戳.自增序列.当前进程号.当前线程 ID
     * 客户端 IP 是 16 进制数字，每两位代表一个十进制的ip段，例如 192.168.1.1 => c0a80101
     *
     * @param request 请求体，用来获取IP
     */
    private String createTraceId(HttpServletRequest request){
        return IpUtils.ipToHex(IpUtils.getIpAddr(request)) + StrUtil.DOT +
                System.currentTimeMillis() + StrUtil.DOT +
                IncreaseUtils.getIncreaseNum() + StrUtil.DOT +
                ManagementFactory.getRuntimeMXBean().getName().split("@")[0] + StrUtil.DOT +
                Thread.currentThread().getId();
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String traceId = createTraceId(request);
        MDC.put(XiuMuConst.TRACE_ID, traceId);
        response.addHeader(XiuMuConst.TRACE_ID, traceId);
        return true;
    }
}
